﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Data;

using NetBay.Core.BusinessEntities;

using Rio.Applications.Web.Services;
using Rio.Framework.Localisation;
using Rio.Framework.Pages.Helpers.Converter;
using Rio.Framework.Pages.ModalControls;

using Telerik.Windows;
using Telerik.Windows.Controls;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Data;

namespace Rio.Framework.Pages.Controls
{
    #region Delegates

    #endregion Delegates

    public partial class ListFolderSearchControl
    {
        #region Fields

        private string labelAlerts;
        private string LabelHeaderColumnNbDoc;
        private string labelMessageDeleteConfirmation;
        private string labelNbrOfFolderResults;

        //Last row
        private GridViewRow m_gvrLastExpandedRow;
        private FolderType m_oFolderTypeSelected;
        private List<Folder> m_olistFolders;
        private Organization m_oOrganizationSelected;
        private QueryableCollectionView m_oSource;
        private SplashScreen m_ssSplashScreen;
        private List<Index> _listIndex = new List<Index>();

        #endregion Fields

        #region Properties

        /// <summary>
        /// Gets or sets the folder type selected.
        /// </summary>
        /// <value>The folder type selected.</value>
        public FolderType FolderTypeSelected
        {
            get { return m_oFolderTypeSelected; }
            set
            {
                m_oFolderTypeSelected = value;
            }
        }

        /// <summary>
        /// Gets or sets the list folders.
        /// </summary>
        /// <value>The list folders.</value>
        public List<Folder> ListFolders
        {
            get { return m_olistFolders; }
            set
            {
                m_olistFolders = value;

                if (value != null)
                {
                    InitGridViewFolderSearch();
                    LoadListFolders();
                }
            }
        }

        /// <summary>
        /// Gets or sets the index of the list.
        /// </summary>
        /// <value>The index of the list.</value>
        public List<Index> ListIndex
        {
            get { return _listIndex; }
            set
            {
                _listIndex = value;
                InitGridViewFolderSearch();
            }
        }

        /// <summary>
        /// Gets or sets the organization selected.
        /// </summary>
        /// <value>The organization selected.</value>
        public Organization OrganizationSelected
        {
            get { return m_oOrganizationSelected; }
            set
            {
                m_oOrganizationSelected = value;
            }
        }

        #endregion Properties

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ListFolderSearchControl" /> class.
        /// </summary>
        public ListFolderSearchControl()
        {
            InitializeComponent();

            //SplashScreen
            m_ssSplashScreen = new SplashScreen();

            InitLabel();

            //Add double click event at the gridview
            GridViewDoc.AddHandler(GridViewCell.CellDoubleClickEvent, new EventHandler<RadRoutedEventArgs>(OnDoubleClick));
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ListFolderSearchControl" /> class.
        /// </summary>
        /// <param name="indexList">The index list.</param>
        public ListFolderSearchControl(List<Index> indexList)
        : this()
        {
            ListIndex = indexList;
        }

        #endregion Constructors

        #region Delegates

        public delegate void LoadSelectedFolderInformationHandler(Folder P_oFolder, FolderType P_oFolderType, Organization P_oOrganization);

        #endregion Delegates

        #region Events

        public event LoadSelectedFolderInformationHandler LoadSelectedFolderInformation;

        #endregion Events

        #region Methods

        /// <summary>
        /// Translation
        /// </summary>
        public void InitLabel()
        {
            LabelHeaderColumnNbDoc = Resx.GetLabel(ResxFolder.NB_DOC);
            m_ssSplashScreen.Message = Resx.GetLabel(ResxCommon.SPLASHSCREEN_MESSAGE);
            labelMessageDeleteConfirmation = Resx.GetLabel(ResxFolder.DELETE_CONFIRMATION_FOLDER);

            labelNbrOfFolderResults = Resx.GetLabel(ResxFolder.NBR_OF_FOLDER_RESULT);
            labelAlerts = Resx.GetLabel(ResxFolder.ALERT_HEADER);
        }

        /// <summary>
        /// Handles the DataLoaded event of the GridViewDoc control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs" /> instance containing the event data.</param>
        private void GridViewDoc_DataLoaded(object sender, EventArgs e)
        {
            GridViewDoc.UnselectAll();
        }

        /// <summary>
        /// Expand row details
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="Telerik.Windows.Controls.GridView.GridViewRowDetailsEventArgs" /> instance containing the event data.</param>
        private void GridViewDoc_RowDetailsVisibilityChanged(object sender, GridViewRowDetailsEventArgs e)
        {
            if (e.Visibility == Visibility.Visible)
            {
                if (( m_gvrLastExpandedRow != null ) && ( m_gvrLastExpandedRow.DetailsVisibility == Visibility.Visible ))
                {
                    m_gvrLastExpandedRow.DetailsVisibility = Visibility.Collapsed;
                }

                m_gvrLastExpandedRow = e.Row;

                //Row detail control selected
                //m_oRowDetailControl = (ListDocumentControl)e.DetailsElement;
                //m_oRowDetailControl.UpdatePageSize(15);

                if (( e.Row != null ) && ( e.Row.Item != null ))
                {
                    //Launch Splash screen
                    m_ssSplashScreen.Show();
                    ModalDialogController.Launch(m_ssSplashScreen);

                    Dictionary<string, string> L_oDict = e.Row.Item as Dictionary<string, string>;
                    if (L_oDict != null)
                    {
                        long L_lFolderIdentifier = long.Parse(L_oDict["Identifier"]);
                        long l_lFolderTypeIdentifier = m_olistFolders.First().FolderTypeIdentifier;

                        //LoadDocumentOnFolder(l_lFolderTypeIdentifier, L_lFolderIdentifier);
                    }
                }
            }
            else
            {
                m_gvrLastExpandedRow = null;
            }
        }

        /// <summary>
        /// Inititialize folder search result GridView
        /// </summary>
        private void InitGridViewFolderSearch()
        {
            GridViewDoc.Columns.Clear();
            GridViewDoc.ItemsSource = null;

            GridViewImageColumn l_oFileIcone = new GridViewImageColumn
            {
                UniqueName = "Folder",
                IsReadOnly = true,
                Header = String.Empty,
                Width = 40,
                DataMemberBinding = new Binding("[NbDoc]")
                {
                    Converter = new FolderToImageConverter()
                }
            };
            GridViewDoc.Columns.Add(l_oFileIcone);

            // Document number column
            GridViewDataColumn m_gvdcNbDocument = new GridViewDataColumn
            {
                IsReadOnly = true,
                MinWidth = 100,
                Header = LabelHeaderColumnNbDoc,
                DataMemberBinding = new Binding("[NbDoc]")
            };
            GridViewDoc.Columns.Add(m_gvdcNbDocument);

            GridViewDataColumn L_gvdcDataColumn;
            foreach (Index t in ListIndex)
            {
                L_gvdcDataColumn = new GridViewDataColumn
                {
                    UniqueName = t.Indentifier.ToString(),
                    IsReadOnly = true,
                    Header = t.IndexLabel,
                    MinWidth = 150
                };

                // the prefix 'index' is need to bind correctly
                //(Identifier is a numeric and the property bind has not to begin with a numeric, else we have a bad behavior with RadGridView such as disappearance filter or disabled grouping column)
                Binding bind = new Binding("[index" + t.Indentifier + "]") { Converter = new IndexValueConverter() };

                L_gvdcDataColumn.DataMemberBinding = bind;
                GridViewDoc.Columns.Add(L_gvdcDataColumn);
            }
        }

        /// <summary>
        /// Initlabels the NBR of folder results.
        /// </summary>
        private void InitlabelNbrOfFolderResults()
        {
            //LabelNbrOfFolderResults.Visibility = Visibility.Visible;
            //LabelNbrOfFolderResults.Text = String.Format(labelNbrOfFolderResults, ListFolders.Count);
        }

        /// <summary>
        /// Enable to load folder list in gridview
        /// </summary>
        private void LoadListFolders()
        {
            //Build a dictionnary list to bind folder and index value into the gridview
            List<Dictionary<string, string>> L_oListRow = new List<Dictionary<string, string>>();
            Dictionary<string, string> L_oDict;

            InitlabelNbrOfFolderResults();

            foreach (Folder f in m_olistFolders)
            {
                L_oDict = new Dictionary<string, string>
                              {
                                  {"Identifier", f.Identifier.ToString()},
                                  {"NbDoc", f.NbDoc.ToString()},
                                  {"NbAlert", f.NbAlert.ToString()}
                              };

                //For every value from ListValues, we have "ID;VALUE" for value list type index and user list type index, and we have "VALUE;VALUE" for the other index type
                //because for value list type index and user list type index we need the value to display and id for identify the value (for the consultation screen for exemple, to select the item in the combobox)
                List<string> L_oIndexesValues = new List<string>(f.ListValues);
                List<Index> L_oIndexes = new List<Index>(f.ListIndex);

                for (int i = 0; i < L_oIndexes.Count; i++)
                {
                    if (L_oIndexes[i].Type.Equals((int)IndexDomainServiceEnums.IndexType.Date))
                    {
                        if (L_oIndexesValues[i] != null && L_oIndexesValues[i] != String.Empty)
                        {
                            L_oDict.Add("index" + L_oIndexes[i].Indentifier, ToDateTime(L_oIndexesValues[i]).ToShortDateString());
                        }
                        else
                        {
                            L_oDict.Add("index" + L_oIndexes[i].Indentifier, L_oIndexesValues[i]);
                        }
                    }
                    else
                    {
                        L_oDict.Add("index" + L_oIndexes[i].Indentifier, L_oIndexesValues[i]);
                    }

                }

                L_oListRow.Add(L_oDict);
            }

            //We need a QueryableCollectionView to manage a datapager with the gridview
            //To know how data are binding, see InitGridViewFolderSearch function
            m_oSource = new QueryableCollectionView(L_oListRow);
            GridViewDoc.ItemsSource = m_oSource;
            DataPagerDoc.Source = m_oSource;
        }

        /// <summary>
        /// Toes the date time.
        /// </summary>
        /// <param name="p_oSource">The p_o source.</param>
        /// <returns></returns>
        private DateTime ToDateTime(string p_oSource)
        {
            DateTime l_oDt;
            return DateTime.TryParse(p_oSource, out l_oDt) ? l_oDt : default(DateTime);
        }

        /// <summary>
        /// Called when [double click].
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="Telerik.Windows.RadRoutedEventArgs" /> instance containing the event data.</param>
        private void OnDoubleClick(object sender, RadRoutedEventArgs e)
        {
            if (e.Source.GetType().Equals(typeof(GridViewCell)))
            {
                Dictionary<string, string> l_oDic = ( (GridViewCell)e.Source ).ParentRow.Item as Dictionary<string, string>;
                if (l_oDic != null)
                {
                    Folder L_oSelectedFolder = m_olistFolders.Where(f => f.Identifier == long.Parse(l_oDic["Identifier"].ToString())).FirstOrDefault();
                    OnLoadSelectedFolderInformation(L_oSelectedFolder, m_oFolderTypeSelected, m_oOrganizationSelected);
                }
            }
        }

        /// <summary>
        /// method for raise the event 'LoadSelectedFolderInformation'
        /// </summary>
        /// <param name="P_oFolder">The p_o folder.</param>
        /// <param name="P_oFolderType">Type of the p_o folder.</param>
        /// <param name="P_oOrganization">The p_o organization.</param>
        private void OnLoadSelectedFolderInformation(Folder P_oFolder, FolderType P_oFolderType, Organization P_oOrganization)
        {
            if (LoadSelectedFolderInformation != null)
                LoadSelectedFolderInformation(P_oFolder, P_oFolderType, P_oOrganization);
        }

        #endregion Methods
    }
}